<template>
  <div class="encasement-execute-page">
    <el-page-header
      content="执行装箱"
      @back="handleBack"
      class="encasement-execute-page__header"
    />
    <el-scrollbar class="encasement-execute-scroll">
      <el-card
        shadow="never"
        class="encasement-execute-card"
        :body-style="{ padding: '18px 24px' }"
        v-loading="detailLoading"
      >
        <div class="meta-strip">
          <div class="meta-strip__item">
            <p class="meta-label">装箱单编号</p>
            <p class="meta-value">{{ form.packingListNo || "—" }}</p>
          </div>
          <div class="meta-strip__item">
            <p class="meta-label">客户</p>
            <p class="meta-value">
              {{ form.customerName || "待选择客户" }}
              <el-tag v-if="form.customerCode" size="small" class="meta-tag">
                {{ form.customerCode }}
              </el-tag>
            </p>
          </div>
          <div class="meta-strip__item">
            <p class="meta-label">关联订单</p>
            <p class="meta-value">{{ form.salesOrderNo || "—" }}</p>
          </div>
          <div class="meta-strip__item">
            <p class="meta-label">箱体体积</p>
            <p class="meta-value meta-value--accent">
              {{ volumeDisplay }}
            </p>
          </div>
        </div>

        <el-alert
          type="info"
          show-icon
          title="请核对基础信息后，再录入箱体尺寸和子箱明细。"
          class="encasement-alert"
        />

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="110px"
          class="encasement-execute-form"
        >
          <section class="form-block">
            <header class="form-block__header">
              <div>
                <p class="form-block__title">基础信息</p>
                <p class="form-block__subtitle">
                  信息来自装箱单，可用于复核与备注
                </p>
              </div>
              <el-tag type="info" size="small">自动同步来源信息</el-tag>
            </header>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="装箱单编号">
                  <el-input v-model="form.packingListNo" disabled />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="系统锁单">
                  <el-switch v-model="form.systemLock" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :lg="8">
                <el-form-item label="装箱单名称">
                  <el-input
                    v-model="form.packingListName"
                    placeholder="自动填充，可手动备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="装箱日期">
                  <el-input v-model="form.packingDate" disabled />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="订单编号(销售)">
                  <el-input v-model="form.salesOrderNo" disabled />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="客户分类">
                  <el-input v-model="form.customerLevel" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12">
                <el-form-item label="客户名称">
                  <el-input v-model="form.customerName" disabled />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12">
                <el-form-item label="客户编号">
                  <el-input v-model="form.customerCode" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="需要同步给库房的注意事项，可在此补充"
              />
            </el-form-item>
          </section>

          <section class="form-block">
            <header class="form-block__header">
              <div>
                <p class="form-block__title">装箱信息</p>
                <p class="form-block__subtitle">尺寸、重量与执行选项</p>
              </div>
              <el-tag v-if="boxVolume" type="success" size="small">
                预估体积：{{ volumeDisplay }}
              </el-tag>
            </header>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="箱子长度(CM)" prop="boxLength">
                  <el-input-number
                    v-model="form.boxLength"
                    :min="0"
                    :controls="false"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="箱子宽度(CM)" prop="boxWidth">
                  <el-input-number
                    v-model="form.boxWidth"
                    :min="0"
                    :controls="false"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="箱子高度(CM)" prop="boxHeight">
                  <el-input-number
                    v-model="form.boxHeight"
                    :min="0"
                    :controls="false"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="净重(KG)" prop="netWeight">
                  <el-input-number
                    v-model="form.netWeight"
                    :min="0"
                    :controls="false"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="毛重(KG)" prop="grossWeight">
                  <el-input-number
                    v-model="form.grossWeight"
                    :min="0"
                    :controls="false"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="8">
                <el-form-item label="包含子箱">
                  <el-switch v-model="form.hasSubBox" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="16">
              <el-col :xs="24" :sm="12">
                <el-form-item label="同步打印标签">
                  <el-switch v-model="form.autoPrintLabel" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12">
                <el-form-item label="自动推送WMS">
                  <el-switch v-model="form.syncToWms" />
                </el-form-item>
              </el-col>
            </el-row>
          </section>

          <section class="form-block">
            <header class="form-block__header">
              <div>
                <p class="form-block__title">子箱信息</p>
                <p class="form-block__subtitle">
                  {{ subBoxSummary.desc }}
                </p>
              </div>
              <div class="form-block__actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEnableSubBox"
                >
                  添加
                </el-button>
                <el-button
                  size="small"
                  @click="handleDisableSubBox"
                  :disabled="!form.hasSubBox"
                >
                  移除
                </el-button>
              </div>
            </header>

            <el-table
              v-if="form.hasSubBox && subBoxInfos.length"
              :data="subBoxInfos"
              border
              size="small"
              class="subbox-header-table"
            >
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column
                prop="packingListNo"
                label="装箱单编号"
                min-width="140"
              />
              <el-table-column
                prop="packingListName"
                label="装箱单名称"
                min-width="160"
              />
              <el-table-column
                prop="packingDate"
                label="装箱日期"
                min-width="120"
              />
              <el-table-column
                prop="salesOrderNo"
                label="订单编号(销售)"
                min-width="160"
              />
              <el-table-column
                prop="customerName"
                label="客户名称"
                min-width="140"
              />
              <el-table-column
                prop="customerCode"
                label="客户编号"
                min-width="120"
              />
              <el-table-column
                prop="boxLength"
                label="箱子长度(CM)"
                width="120"
              />
              <el-table-column
                prop="boxWidth"
                label="箱子宽度(CM)"
                width="120"
              />
              <el-table-column
                prop="boxHeight"
                label="箱子高度(CM)"
                width="120"
              />
              <el-table-column prop="netWeight" label="净重(KG)" width="110" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveSubBoxInfo($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="subbox-empty-tip">
              <el-empty description='暂无子箱信息，请点击上方"添加"创建' />
            </div>
          </section>

          <section class="form-block">
            <header class="form-block__header">
              <div>
                <p class="form-block__title">装箱清单</p>
                <p class="form-block__subtitle">根据子箱维护产品清单信息</p>
              </div>
              <div class="form-block__actions">
                <el-button size="small" @click="handleImport"> 导入 </el-button>
                <el-button type="primary" size="small" @click="handleAddSubBox">
                  添加
                </el-button>
                <el-button
                  size="small"
                  @click="handleBatchRemove"
                  :disabled="!selectedDetails.length"
                >
                  移除
                </el-button>
              </div>
            </header>

            <el-table
              v-if="form.subBoxes.length"
              ref="detailTableRef"
              :data="form.subBoxes"
              border
              size="small"
              class="subbox-table"
              @selection-change="handleDetailSelectionChange"
            >
              <el-table-column type="selection" width="50" />
              <el-table-column type="index" width="60" label="序号" />
              <el-table-column label="产品编号" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.productCode" />
                </template>
              </el-table-column>
              <el-table-column label="产品名称" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.productName" />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.specModel" />
                </template>
              </el-table-column>
              <el-table-column label="产品类型" min-width="120">
                <template #default="{ row }">
                  <el-input v-model="row.productType" />
                </template>
              </el-table-column>
              <el-table-column label="单位" width="90">
                <template #default="{ row }">
                  <el-input v-model="row.unit" />
                </template>
              </el-table-column>
              <el-table-column label="工单号" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.workOrderCode" />
                </template>
              </el-table-column>
              <el-table-column label="工单名称" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.workOrderName" />
                </template>
              </el-table-column>
              <el-table-column label="批次号" min-width="140">
                <template #default="{ row }">
                  <el-input v-model="row.batchNo" />
                </template>
              </el-table-column>
              <el-table-column label="有效期" min-width="150">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.validDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                  />
                </template>
              </el-table-column>
              <el-table-column label="装箱数量" width="120">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.packingQuantity"
                    :min="0"
                    :controls="false"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="160">
                <template #default="{ row }">
                  <el-input v-model="row.remark" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="90" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveSubBox($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="subbox-empty-tip">
              <el-empty description='暂无装箱清单，请点击上方"添加"维护' />
            </div>
          </section>
        </el-form>

        <el-dialog
          v-model="subBoxSelector.visible"
          title="添加装箱单"
          width="900px"
          :close-on-click-modal="false"
        >
          <div class="subbox-selector__search">
            <el-input
              v-model="subBoxSelector.query.packingListKeyword"
              placeholder="请输入装箱单编号/名称"
              clearable
            />
            <el-input
              v-model="subBoxSelector.query.customerKeyword"
              placeholder="请输入客户名称/编号"
              clearable
            />
            <el-date-picker
              v-model="subBoxSelector.query.packingDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择装箱日期"
              clearable
            />
            <div class="subbox-selector__search-actions">
              <el-button @click="handleSubBoxReset">重置</el-button>
              <el-button type="primary" @click="handleSubBoxSearch">
                查询
              </el-button>
            </div>
          </div>
          <el-table
            v-loading="subBoxSelector.loading"
            :data="subBoxSelector.list"
            border
            size="small"
            @selection-change="handleSubBoxSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column
              prop="packingListName"
              label="装箱单名称"
              min-width="150"
            />
            <el-table-column
              prop="packingListNo"
              label="装箱单编号"
              min-width="140"
            />
            <el-table-column
              prop="packingDate"
              label="装箱日期"
              min-width="120"
            >
              <template #default="{ row }">
                {{ row.packingDate ? formatDate(row.packingDate) : "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="salesOrderNo"
              label="订单编号"
              min-width="150"
            />
            <el-table-column label="客户名称" min-width="140">
              <template #default="{ row }">
                {{ row.customerName || "-" }}
              </template>
            </el-table-column>
            <el-table-column
              prop="customerCode"
              label="客户编号"
              min-width="120"
            />
            <el-table-column
              prop="boxLength"
              label="箱子长度(CM)"
              min-width="120"
            />
            <el-table-column
              prop="boxWidth"
              label="箱子宽度(CM)"
              min-width="120"
            />
            <el-table-column
              prop="boxHeight"
              label="箱子高度(CM)"
              min-width="120"
            />
            <el-table-column
              prop="netWeight"
              label="净重(KG)"
              min-width="100"
            />
          </el-table>
          <div class="subbox-selector__pager">
            <el-pagination
              v-model:current-page="subBoxSelector.pagination.pageIndex"
              v-model:page-size="subBoxSelector.pagination.pageSize"
              :page-sizes="[5, 10, 20]"
              background
              layout="total, sizes, prev, pager, next"
              :total="subBoxSelector.pagination.totalCount"
              @size-change="handleSubBoxSizeChange"
              @current-change="handleSubBoxPageChange"
            />
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="subBoxSelector.visible = false"
                >取 消</el-button
              >
              <el-button type="primary" @click="handleSubBoxConfirm">
                确 定
              </el-button>
            </span>
          </template>
        </el-dialog>

        <el-dialog
          v-model="productSelector.visible"
          title="添加产品"
          width="1000px"
          :close-on-click-modal="false"
        >
          <div class="selector-search-row">
            <el-input
              v-model="productSelector.query.workOrderKeyword"
              placeholder="请输入工单编号/名称"
              clearable
            />
            <el-input
              v-model="productSelector.query.productKeyword"
              placeholder="请输入产品编号/名称"
              clearable
            />
            <el-select
              v-model="productSelector.query.productType"
              placeholder="请选择产品类型"
              clearable
              @change="handleProductFilterChange"
              @clear="handleProductFilterChange"
            >
              <el-option
                v-for="item in productTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-select
              v-model="productSelector.query.unit"
              placeholder="请选择单位"
              clearable
              @change="handleProductFilterChange"
              @clear="handleProductFilterChange"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <div class="selector-search-row__actions">
              <el-button @click="handleProductReset">重置</el-button>
              <el-button type="primary" @click="handleProductSearch">
                查询
              </el-button>
            </div>
          </div>
          <el-table
            v-loading="productSelector.loading"
            :data="productSelector.list"
            border
            size="small"
            @selection-change="handleProductSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column
              prop="workOrderNo"
              label="工单编号"
              min-width="140"
            />
            <el-table-column
              prop="workOrderName"
              label="工单名称"
              min-width="150"
            />
            <el-table-column
              prop="productName"
              label="产品名称"
              min-width="150"
            />
            <el-table-column
              prop="productNo"
              label="产品编号"
              min-width="140"
            />
            <el-table-column
              prop="specification"
              label="规格型号"
              min-width="120"
            />
            <el-table-column
              prop="productType"
              label="产品类型"
              min-width="120"
            />
            <el-table-column prop="unit" label="单位" width="90" />
            <el-table-column prop="batchNo" label="批次号" min-width="140" />
            <el-table-column label="有效期" min-width="130">
              <template #default="{ row }">
                {{ row.validDate || "-" }}
              </template>
            </el-table-column>
          </el-table>
          <div class="selector-pager">
            <el-pagination
              v-model:current-page="productSelector.pagination.pageIndex"
              v-model:page-size="productSelector.pagination.pageSize"
              :page-sizes="[5, 10, 20]"
              background
              layout="total, sizes, prev, pager, next"
              :total="productSelector.pagination.totalCount"
              @size-change="handleProductSizeChange"
              @current-change="handleProductPageChange"
            />
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="productSelector.visible = false"
                >取 消</el-button
              >
              <el-button type="primary" @click="handleProductConfirm">
                确 定
              </el-button>
            </span>
          </template>
        </el-dialog>

        <div class="page-footer">
          <el-button @click="handleBack">取 消</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            确 认 执 行
          </el-button>
        </div>
      </el-card>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";

interface SubBoxItem {
  productCode: string;
  productName: string;
  orderCode: string;
  specModel: string;
  productType: string;
  unit: string;
  workOrderCode: string;
  workOrderName: string;
  batchNo: string;
  validDate: string | null;
  packingQuantity: number | null;
  remark: string;
}

interface ExecuteForm {
  packingListNo: string;
  packingListName: string;
  packingDate: string;
  salesOrderNo: string;
  customerName: string;
  customerCode: string;
  customerLevel: string;
  remark: string;
  boxLength: number | null;
  boxWidth: number | null;
  boxHeight: number | null;
  netWeight: number | null;
  grossWeight: number | null;
  hasSubBox: boolean;
  systemLock: boolean;
  autoPrintLabel: boolean;
  syncToWms: boolean;
  subBoxes: SubBoxItem[];
}

const route = useRoute();
const router = useRouter();

const formRef = ref<FormInstance>();
const detailTableRef = ref();

interface EncasementListItem {
  packingListId: string | number | null;
  packingListNo: string;
  packingListName: string;
  packingDate: string;
  salesOrderNo: string;
  customerName: string;
  customerCode: string;
  boxLength: number | null;
  boxWidth: number | null;
  boxHeight: number | null;
  netWeight: number | null;
}

interface ProductStorageItem {
  id: string | number;
  inboundOrderNo: string;
  inboundOrderName: string;
  inboundDate: string;
  workOrderName: string;
  workOrderNo: string;
  productName: string;
  productNo: string;
  specification: string;
  productTypeId: number | null;
  unit: string;
  batchNo: string;
  productType: string;
  validDate: string | null;
  quantity: number;
}
const submitting = ref(false);
const detailLoading = ref(false);

const form = reactive<ExecuteForm>({
  packingListNo: "",
  packingListName: "",
  packingDate: "",
  salesOrderNo: "",
  customerName: "",
  customerCode: "",
  customerLevel: "系统默认客户",
  remark: "",
  boxLength: null,
  boxWidth: null,
  boxHeight: null,
  netWeight: null,
  grossWeight: null,
  hasSubBox: false,
  systemLock: true,
  autoPrintLabel: true,
  syncToWms: true,
  subBoxes: [],
});

const createSubBoxItem = (): SubBoxItem => ({
  productCode: "",
  productName: "",
  orderCode: form.salesOrderNo,
  specModel: "",
  productType: "",
  unit: "",
  workOrderCode: "",
  workOrderName: "",
  batchNo: "",
  validDate: null,
  packingQuantity: 1,
  remark: "",
});

const rules: FormRules = {
  boxLength: [{ required: true, message: "请输入箱子长度", trigger: "blur" }],
  boxWidth: [{ required: true, message: "请输入箱子宽度", trigger: "blur" }],
  boxHeight: [{ required: true, message: "请输入箱子高度", trigger: "blur" }],
  netWeight: [{ required: true, message: "请输入净重", trigger: "blur" }],
  grossWeight: [{ required: true, message: "请输入毛重", trigger: "blur" }],
};

const previewData = computed(() => form.subBoxes);

const volumeDisplay = computed(() => {
  if (!form.boxLength || !form.boxWidth || !form.boxHeight) {
    return "待计算";
  }
  const volume =
    Number(form.boxLength || 0) *
    Number(form.boxWidth || 0) *
    Number(form.boxHeight || 0);
  return `${volume.toLocaleString()} cm³`;
});

const boxVolume = computed(() => {
  if (!form.boxLength || !form.boxWidth || !form.boxHeight) return 0;
  return (
    Number(form.boxLength || 0) *
    Number(form.boxWidth || 0) *
    Number(form.boxHeight || 0)
  );
});

const subBoxSummary = computed(() => {
  if (!form.hasSubBox) {
    return { desc: "目前关闭子箱，直接按整箱执行" };
  }
  const total = form.subBoxes.reduce(
    (sum, item) => sum + (Number(item.packingQuantity) || 0),
    0
  );
  const uniqueProducts = new Set(
    form.subBoxes.map((item) => item.productCode || item.productName)
  ).size;
  return {
    desc: `共 ${form.subBoxes.length} 条，${uniqueProducts} 种产品，合计 ${total} 件`,
  };
});

const subBoxInfos = ref<EncasementListItem[]>([]);
const selectedDetails = ref<SubBoxItem[]>([]);

const productTypeOptions = computed(() => {
  const set = new Set<string>();
  productSelector.rawList.forEach((item) => {
    if (item.productType) {
      set.add(item.productType);
    }
  });
  return Array.from(set);
});

const unitOptions = computed(() => {
  const set = new Set<string>();
  productSelector.rawList.forEach((item) => {
    if (item.unit) {
      set.add(item.unit);
    }
  });
  return Array.from(set);
});

const subBoxSelector = reactive({
  visible: false,
  loading: false,
  list: [] as EncasementListItem[],
  selection: [] as EncasementListItem[],
  query: {
    packingListKeyword: "",
    customerKeyword: "",
    packingDate: "",
  },
  pagination: {
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
  },
});

const productSelector = reactive({
  visible: false,
  loading: false,
  rawList: [] as ProductStorageItem[],
  list: [] as ProductStorageItem[],
  selection: [] as ProductStorageItem[],
  query: {
    workOrderKeyword: "",
    productKeyword: "",
    productType: "",
    unit: "",
  },
  pagination: {
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
  },
});

const resetForm = () => {
  form.boxLength = null;
  form.boxWidth = null;
  form.boxHeight = null;
  form.netWeight = null;
  form.grossWeight = null;
  form.hasSubBox = false;
  form.subBoxes = [];
};

const formatDate = (value?: string) => {
  if (!value) return "";
  const formatted = dayjs(value);
  return formatted.isValid() ? formatted.format("YYYY-MM-DD") : value;
};

const loadPackingListDetail = async () => {
  if (!form.packingListNo) return;
  detailLoading.value = true;
  try {
    const res: any = await https.Reads.get("/Warehouse/EncasementList", {
      params: {
        PackingListKeyword: form.packingListNo,
        PageIndex: 1,
        PageSize: 1,
      },
    });
    if (res.data?.code === 1 && Array.isArray(res.data.data)) {
      const detail = res.data.data[0];
      if (detail) {
        form.packingListName =
          detail.packingListName || form.packingListName || "";
        form.salesOrderNo = detail.salesOrderNo || form.salesOrderNo || "";
        form.customerName = detail.customerId || form.customerName || "";
        form.customerCode = detail.customerCode || form.customerCode || "";
        form.packingDate = formatDate(detail.packingDate) || form.packingDate;
        form.boxLength =
          detail.boxLength ?? form.boxLength ?? detail.boxLength ?? null;
        form.boxWidth =
          detail.boxWidth ?? form.boxWidth ?? detail.boxWidth ?? null;
        form.boxHeight =
          detail.boxHeight ?? form.boxHeight ?? detail.boxHeight ?? null;
        form.netWeight =
          detail.netWeight ?? form.netWeight ?? detail.netWeight ?? null;
        form.grossWeight =
          detail.grossWeight ?? form.grossWeight ?? detail.grossWeight ?? null;
        form.hasSubBox = Boolean(detail.hasSubBox);
      } else {
        ElMessage.warning("未找到装箱单基础信息，已使用传入数据");
      }
    } else {
      ElMessage.error(res.data?.msg || "获取装箱单信息失败");
    }
  } catch (error) {
    console.error("获取装箱单信息失败:", error);
    ElMessage.error("获取装箱单信息失败，请稍后重试");
  } finally {
    detailLoading.value = false;
  }
};

onMounted(() => {
  const packingListNo = (route.query.packingListNo as string) || "";
  if (!packingListNo) {
    ElMessageBox.alert("缺少装箱单编号，无法执行装箱", "提示", {
      type: "warning",
    }).then(() => {
      handleBack();
    });
    return;
  }
  form.packingListNo = packingListNo;
  form.packingListName = (route.query.packingListName as string) || "";
  form.salesOrderNo = (route.query.salesOrderNo as string) || "";
  form.customerName = (route.query.customerName as string) || "";
  form.customerCode = (route.query.customerCode as string) || "";
  form.packingDate = formatDate(route.query.packingDate as string);
  loadPackingListDetail();
});

watch(
  () => form.hasSubBox,
  (val, oldVal) => {
    if (val && !oldVal && !form.subBoxes.length) {
      form.subBoxes.push(createSubBoxItem());
    }
    if (!val) {
      form.subBoxes = [];
      subBoxInfos.value = [];
    }
  }
);

const normalizeEncasementRow = (row: any): EncasementListItem => ({
  packingListId: row.packingListId ?? row.id ?? null,
  packingListNo: row.packingListNo ?? row.PackingListNo ?? "",
  packingListName: row.packingListName ?? row.PackingListName ?? "",
  packingDate: row.packingDate ?? row.PackingDate ?? "",
  salesOrderNo: row.salesOrderNo ?? row.SalesOrderNo ?? "",
  customerName:
    row.customerName || row.customer_name || row.customerId || row.CustomerName,
  customerCode: row.customerCode ?? row.CustomerCode ?? "",
  boxLength:
    Number(row.boxLength ?? row.BoxLength ?? form.boxLength ?? 0) || null,
  boxWidth: Number(row.boxWidth ?? row.BoxWidth ?? form.boxWidth ?? 0) || null,
  boxHeight:
    Number(row.boxHeight ?? row.BoxHeight ?? form.boxHeight ?? 0) || null,
  netWeight: Number(row.netWeight ?? row.NetWeight ?? 0) || null,
});

const loadSubBoxOptions = () => {
  subBoxSelector.loading = true;
  const params: Record<string, any> = {
    PageIndex: subBoxSelector.pagination.pageIndex,
    PageSize: subBoxSelector.pagination.pageSize,
  };
  if (subBoxSelector.query.packingListKeyword) {
    params.PackingListKeyword = subBoxSelector.query.packingListKeyword;
  }
  if (subBoxSelector.query.customerKeyword) {
    params.CustomerKeyword = subBoxSelector.query.customerKeyword;
  }
  if (subBoxSelector.query.packingDate) {
    params.PackingDate = subBoxSelector.query.packingDate;
  }

  https.Reads.get("/Warehouse/EncasementList", { params })
    .then((res: any) => {
      if (res.data?.code === 1) {
        subBoxSelector.list = (res.data.data || []).map((item: any) =>
          normalizeEncasementRow(item)
        );
        subBoxSelector.pagination.totalCount = res.data.totalCount || 0;
      } else {
        subBoxSelector.list = [];
        subBoxSelector.pagination.totalCount = 0;
        ElMessage.error(res.data?.msg || "获取装箱列表失败");
      }
    })
    .catch((err: any) => {
      console.error("加载子箱信息失败:", err);
      subBoxSelector.list = [];
      subBoxSelector.pagination.totalCount = 0;
      ElMessage.error("获取装箱列表失败，请稍后重试");
    })
    .finally(() => {
      subBoxSelector.loading = false;
    });
};

const handleSubBoxSearch = () => {
  subBoxSelector.pagination.pageIndex = 1;
  loadSubBoxOptions();
};

const handleSubBoxReset = () => {
  subBoxSelector.query.packingListKeyword = "";
  subBoxSelector.query.customerKeyword = "";
  subBoxSelector.query.packingDate = "";
  handleSubBoxSearch();
};

const handleSubBoxPageChange = (page: number) => {
  subBoxSelector.pagination.pageIndex = page;
  loadSubBoxOptions();
};

const handleSubBoxSizeChange = (size: number) => {
  subBoxSelector.pagination.pageSize = size;
  subBoxSelector.pagination.pageIndex = 1;
  loadSubBoxOptions();
};

const handleSubBoxSelectionChange = (rows: EncasementListItem[]) => {
  subBoxSelector.selection = rows;
};

const handleSubBoxConfirm = () => {
  if (!subBoxSelector.selection.length) {
    ElMessage.warning("请至少选择一条装箱单");
    return;
  }
  const existingSet = new Set(
    subBoxInfos.value.map((item) => item.packingListNo)
  );
  const toAppend = subBoxSelector.selection.filter(
    (item) => item.packingListNo && !existingSet.has(item.packingListNo)
  );
  if (!toAppend.length) {
    ElMessage.info("选择的装箱单已存在于子箱信息中");
    return;
  }
  subBoxInfos.value = [...subBoxInfos.value, ...toAppend];
  form.hasSubBox = true;
  if (!form.subBoxes.length) {
    form.subBoxes.push(createSubBoxItem());
  }
  subBoxSelector.visible = false;
};

const handleEnableSubBox = () => {
  subBoxSelector.visible = true;
  subBoxSelector.selection = [];
  handleSubBoxSearch();
};

const handleDisableSubBox = () => {
  if (!form.hasSubBox) return;
  ElMessageBox.confirm("确定要移除子箱信息并清空装箱清单吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      form.hasSubBox = false;
      form.subBoxes = [];
      selectedDetails.value = [];
      subBoxInfos.value = [];
    })
    .catch(() => {});
};

const handleImport = () => {
  ElMessage.info("导入功能待接入模板映射，当前仅支持手动录入");
};

const handleAddSubBox = () => {
  form.hasSubBox = true;
  productSelector.visible = true;
  productSelector.selection = [];
  handleProductSearch();
};

const handleDetailSelectionChange = (rows: SubBoxItem[]) => {
  selectedDetails.value = rows;
};

const handleBatchRemove = () => {
  if (!selectedDetails.value.length) {
    ElMessage.warning("请先勾选需要移除的清单行");
    return;
  }
  const toDelete = new Set(selectedDetails.value);
  form.subBoxes = form.subBoxes.filter((x) => !toDelete.has(x));
  selectedDetails.value = [];
  if (!form.subBoxes.length) {
    form.hasSubBox = false;
  }
};

const handleRemoveSubBoxInfo = (index: number) => {
  subBoxInfos.value.splice(index, 1);
  if (!subBoxInfos.value.length) {
    form.hasSubBox = false;
  }
};

const normalizeProductRow = (item: any): ProductStorageItem => ({
  id: item.id ?? item.Id ?? dayjs().valueOf(),
  inboundOrderNo: item.inboundOrderNo ?? item.InboundOrderNo ?? "",
  inboundOrderName: item.inboundOrderName ?? item.InboundOrderName ?? "",
  inboundDate: formatDate(item.inboundDate ?? item.InboundDate) || "",
  workOrderName: item.workOrderName ?? item.WorkOrderName ?? "",
  workOrderNo: item.workOrderNo ?? item.WorkOrderNo ?? "",
  productName: item.productName ?? item.ProductName ?? "",
  productNo: item.productNo ?? item.ProductNo ?? "",
  specification: item.specification ?? item.Specification ?? "",
  productTypeId: Number(item.productTypeId ?? item.ProductTypeId ?? 0) || null,
  unit: item.unit ?? item.Unit ?? "",
  batchNo: item.batchNo ?? item.BatchNo ?? "",
  productType:
    Number(item.productTypeId ?? item.ProductTypeId) === 1
      ? "成品"
      : Number(item.productTypeId ?? item.ProductTypeId) === 2
      ? "半成品"
      : "",
  validDate: item.expiryDate
    ? formatDate(item.expiryDate ?? item.ExpiryDate)
    : null,
  quantity: Number(item.inboundQuantity ?? item.InboundQuantity ?? 1) || 1,
});

const applyProductFilter = () => {
  let rows = [...productSelector.rawList];
  if (productSelector.query.productType) {
    rows = rows.filter((row) =>
      (row.productType || "")
        .toLowerCase()
        .includes(productSelector.query.productType.toLowerCase())
    );
  }
  if (productSelector.query.unit) {
    rows = rows.filter((row) =>
      (row.unit || "")
        .toLowerCase()
        .includes(productSelector.query.unit.toLowerCase())
    );
  }
  productSelector.list = rows;
};

const loadProductOptions = () => {
  productSelector.loading = true;
  const params: Record<string, any> = {
    PageIndex: productSelector.pagination.pageIndex,
    PageSize: productSelector.pagination.pageSize,
  };
  if (productSelector.query.workOrderKeyword) {
    params.InboundCodeName = productSelector.query.workOrderKeyword;
  }
  if (productSelector.query.productKeyword) {
    params.ProductKeyword = productSelector.query.productKeyword;
  }
  https.Reads.get("/Warehouse/ProductStorageList", { params })
    .then((res: any) => {
      if (res.data?.code === 1) {
        const rows = (res.data.data || []).map((item: any) =>
          normalizeProductRow(item)
        );
        productSelector.rawList = rows;
        applyProductFilter();
        productSelector.pagination.totalCount = res.data.totalCount || 0;
      } else {
        productSelector.rawList = [];
        productSelector.list = [];
        productSelector.pagination.totalCount = 0;
        ElMessage.error(res.data?.msg || "获取产品入库列表失败");
      }
    })
    .catch((err: any) => {
      console.error("加载产品数据失败:", err);
      productSelector.rawList = [];
      productSelector.list = [];
      productSelector.pagination.totalCount = 0;
      ElMessage.error("获取产品入库列表失败，请稍后重试");
    })
    .finally(() => {
      productSelector.loading = false;
    });
};

const handleProductSearch = () => {
  productSelector.pagination.pageIndex = 1;
  loadProductOptions();
};

const handleProductReset = () => {
  productSelector.query.workOrderKeyword = "";
  productSelector.query.productKeyword = "";
  productSelector.query.productType = "";
  productSelector.query.unit = "";
  handleProductSearch();
};

const handleProductFilterChange = () => {
  applyProductFilter();
};

const handleProductPageChange = (page: number) => {
  productSelector.pagination.pageIndex = page;
  loadProductOptions();
};

const handleProductSizeChange = (size: number) => {
  productSelector.pagination.pageSize = size;
  productSelector.pagination.pageIndex = 1;
  loadProductOptions();
};

const handleProductSelectionChange = (rows: ProductStorageItem[]) => {
  productSelector.selection = rows;
};

const mapProductToSubBox = (item: ProductStorageItem): SubBoxItem => ({
  productCode: item.productNo,
  productName: item.productName,
  orderCode: item.workOrderNo || form.salesOrderNo,
  specModel: item.specification,
  productType: item.productType,
  unit: item.unit,
  workOrderCode: item.workOrderNo,
  workOrderName: item.workOrderName,
  batchNo: item.batchNo,
  validDate: item.validDate,
  packingQuantity: item.quantity,
  remark: "",
});

const handleProductConfirm = () => {
  if (!productSelector.selection.length) {
    ElMessage.warning("请至少选择一条产品记录");
    return;
  }
  form.hasSubBox = true;
  const existingKeys = new Set(
    form.subBoxes.map(
      (item) => `${item.productCode}_${item.batchNo}_${item.workOrderCode}`
    )
  );
  const newItems: SubBoxItem[] = [];
  productSelector.selection.forEach((row) => {
    if (!row.productNo) return;
    const key = `${row.productNo}_${row.batchNo}_${row.workOrderNo}`;
    if (existingKeys.has(key)) return;
    existingKeys.add(key);
    newItems.push(mapProductToSubBox(row));
  });

  if (!newItems.length) {
    ElMessage.info("选择的产品已全部存在于装箱清单中");
    return;
  }
  form.subBoxes.push(...newItems);
  productSelector.visible = false;
  productSelector.selection = [];
};

const handleClearSubBoxes = () => {
  if (!form.subBoxes.length) return;
  ElMessageBox.confirm("确定要清空全部子箱信息吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      form.subBoxes = [];
      form.hasSubBox = false;
    })
    .catch(() => {});
};

const handleRemoveSubBox = (index: number) => {
  form.subBoxes.splice(index, 1);
};

const handleBack = () => {
  router.back();
};

const handlePreview = () => {
  if (!previewData.value.length) {
    ElMessage.warning("请先录入子箱信息");
    return;
  }
  ElMessage.info("已根据当前数据生成预览，请在下表确认");
};

const refreshDetail = () => {
  loadPackingListDetail();
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;

    if (form.hasSubBox && form.subBoxes.length === 0) {
      ElMessage.warning("开启包含子箱后，请至少添加一条子箱信息");
      return;
    }

    const payload = {
      PackingListNo: form.packingListNo,
      BoxLength: Number(form.boxLength) || 0,
      BoxWidth: Number(form.boxWidth) || 0,
      BoxHeight: Number(form.boxHeight) || 0,
      NetWeight: Number(form.netWeight) || 0,
      GrossWeight: Number(form.grossWeight) || 0,
      SubBoxes: form.hasSubBox
        ? form.subBoxes.map((x) => ({
            ProductCode: x.productCode,
            ProductName: x.productName,
            OrderCode: x.orderCode,
            SpecModel: x.specModel,
            ProductType: x.productType,
            Unit: x.unit,
            WorkOrderCode: x.workOrderCode,
            WorkOrderName: x.workOrderName,
            BatchNo: x.batchNo,
            ValidDate: x.validDate,
            PackingQuantity: Number(x.packingQuantity) || 0,
            Remark: x.remark,
          }))
        : [],
    };

    try {
      submitting.value = true;
      const res: any = await https.Writes.put(
        "/Warehouse/EncasementExecute",
        payload
      );
      if (res.data && res.data.code === 1) {
        ElMessage.success(res.data.msg || "执行装箱成功");
        resetForm();
        router.push("/Encasementlist");
      } else {
        ElMessage.error(res.data?.msg || "执行装箱失败");
      }
    } catch (error) {
      console.error("执行装箱失败:", error);
      ElMessage.error("执行装箱失败，请稍后重试");
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style scoped>
.encasement-execute-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 0 16px 16px;
}

.encasement-execute-scroll {
  /* 让内容随整页滚动，而不是在组件内再次限制高度 */
  max-height: none;
  padding-right: 6px;
}

.encasement-execute-card {
  border-radius: 14px;
  border: 1px solid #eef1f5;
}

.meta-strip {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  margin-bottom: 14px;
}

.meta-strip__item {
  padding: 10px 12px;
  border: 1px dashed #dce1ec;
  border-radius: 10px;
  background-color: #f8fafc;
}

.meta-label {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.meta-value {
  margin: 6px 0 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-value--accent {
  color: #2f54eb;
}

.meta-tag {
  border-radius: 6px;
}

.encasement-alert {
  margin-bottom: 18px;
}

.encasement-execute-form {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.form-block {
  padding: 16px 18px;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 6px 16px rgba(31, 45, 61, 0.04);
}

.form-block__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
  flex-wrap: wrap;
}

.form-block__title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.form-block__subtitle {
  margin: 4px 0 0;
  font-size: 13px;
  color: #909399;
}

.form-block__actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.subbox-table :deep(.el-input),
.subbox-table :deep(.el-input-number) {
  width: 100%;
}

.subbox-empty-tip {
  padding: 24px 0;
}

.subbox-selector__search {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.subbox-selector__search .el-input,
.subbox-selector__search .el-date-editor {
  flex: 1 1 220px;
}

.subbox-selector__search-actions {
  display: flex;
  gap: 8px;
}

.subbox-selector__pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.selector-search-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  margin-bottom: 14px;
  align-items: center;
}

.selector-search-row__actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.selector-pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.page-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>
